/**
  * Copyright (c) CSIRO Australia, 2009
  *
  * @author $Author: jia020 $
  * @version $Id: DynamicGrid.java 643 2009-05-20 00:20:55Z jia020 $
  */
package au.csiro.nt.pdsp.client;

import com.gwtext.client.data.*;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.GridPanel;
import com.google.gwt.xml.client.*;
/**
 * DynamicGrid create dynamic columns in grid according to the metadata specification in XML data source. 
 *
 */
public class DynamicGrid extends GridPanel{
  /**
   * data store for grid.
   */
	public Store store = null;
	/**
	 * Construct grid according xml data
	 * @param xml XML records with metadata specification.
	 */		
	public DynamicGrid(String xml) {
		super();
		int width = 100;
		int totalwidth = 0;
		com.google.gwt.xml.client.Document doc = XMLParser.parse(xml);
		
		NodeList sections = doc.getElementsByTagName(PdspConst.XMLTAG_COLUMN);
		int numSections = sections.getLength();
		FieldDef[] fieldDef = new FieldDef[numSections];
		ColumnConfig[] columnConfigs = new ColumnConfig[numSections];
		for (int i = 0; i < numSections; i++) {
			Element section = (Element) sections.item(i); // A <sect1>
			String name = section.getAttribute(PdspConst.XMLTAG_NAME);
			String type = section.getAttribute(PdspConst.XMLTAG_TYPE);
			if (type.equalsIgnoreCase("string"))
				fieldDef[i] = new StringFieldDef(name);
			else if (type.equalsIgnoreCase("float"))
				fieldDef[i] = new FloatFieldDef(name);
			else if (type.equalsIgnoreCase("integer"))
				fieldDef[i] = new IntegerFieldDef(name);			
			else if (type.equalsIgnoreCase("boolean"))
				fieldDef[i] = new BooleanFieldDef(name);
			else if (type.equalsIgnoreCase("date"))
				fieldDef[i] = new DateFieldDef(name, name, "m-d-Y");
			columnConfigs[i] = new ColumnConfig(name, name, width, true);
			totalwidth += width;
		}
		RecordDef recordDef = new RecordDef(fieldDef);
		ColumnModel columnModel = new ColumnModel(columnConfigs);

		XmlReader reader = new XmlReader("record", recordDef);
		store = new Store(reader);
		store.loadXmlData(xml, true);

		this.setStore(store);
		this.setColumnModel(columnModel);
		this.setTitle("Result:");
		this.setWidth(totalwidth + 100);
		this.setHeight(350);
		this.stripeRows(true);
		this.setFrame(true);
		// grid.setAutoExpandColumn("common");
		this.setIconCls("grid-icon");
	}

}
